import SWDA from './core/index.js'


Bitmap.prototype.clone = function (beforeDrawCallback = () => { }) {
	const { width, height } = this
	const newBitmap = new Bitmap(width, height)
	beforeDrawCallback(newBitmap)
	newBitmap.blt(this, 0, 0, width, height, 0, 0)
	return newBitmap
}

Bitmap.prototype.map2AlphaBitmap = function (alpha = 255) {
	return this.clone(bitmap => bitmap.paintOpacity = alpha)
}

Bitmap.prototype.splitRGB = function (color) {
	// 16进制颜色值的正则
	const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
	// 把颜色值变成小写
	let hex = color.toLowerCase();
	if (color[0] == '#') {
		if (reg.test(hex)) {
			// 如果只有三位的值，需变成六位，如：#fff => #ffffff
			if (hex.length === 4) {
				let hexNew = "#";
				for (let i = 1; i < 4; i += 1) {
					hexNew += hex.slice(i, i + 1).concat(hex.slice(i, i + 1));
				}
				hex = hexNew;
			}

			// 处理六位的颜色值，转为RGB
			let colorChange = [];
			for (let i = 1; i < 7; i += 2) {
				colorChange.push(parseInt("0x" + color.slice(i, i + 2)));
			}
			color = "rgb(" + colorChange.join(",") + ")";
		}
	}

	const rgba = color.replace(/(?:\(|\)|rgba|rgb|RGB)*/g, "").split(",");
	return rgba;
};

Bitmap.prototype.brightness = function (color) {
	var rgba = this.splitRGB(color);
	return Math.round(((rgba[0] * 299) + (rgba[1] * 587) + (rgba[2] * 114)) / 1000);
}

Bitmap.prototype._drawTextOutline = function (text, tx, ty, maxWidth) {

	SWDA.drawTextOutline.call(this, text, tx, ty, maxWidth);
	var context = this._context;
	// 判断颜色
	var brightness = this.brightness(this.textColor);

	// 深色描白边
	if (brightness <= 100) {
		context.strokeStyle = 'rgba(255, 255, 255, 0.5)';//描白边

	} else if (brightness == 255) {
		context.strokeStyle = 'rgba(0, 0, 0, 0.5)';
	} else {
		// 浅色描加深边
		var rgba = this.splitRGB(this.textColor);
		var r = Math.round(0.3 * rgba[0]);
		var g = Math.round(0.3 * rgba[1]);
		var b = Math.round(0.3 * rgba[2]);

		var newcolor = 'rgba(' + r + ', ' + g + ', ' + b + ', 1)';
		context.strokeStyle = newcolor;	//描加深边
	}
	context.lineWidth = this.outlineWidth + 2;
	context.lineJoin = 'round';
	context.strokeText(text, tx, ty, maxWidth);

	// 不是白色，加粗
	if (brightness <= 100) {
		context.strokeStyle = this.textColor;
		context.lineWidth = this.outlineWidth;
		context.lineJoin = 'round';
		context.strokeText(text, tx, ty, maxWidth);
	}

};



// 当没有读取到对应资源时，可以读取默认图片的行为
Bitmap.prototype.setDefault = function (url, isIgnore = false) {
	this._defaultUrl = url
	this._isIgnore = isIgnore
}


Bitmap.prototype._onDefaultError = function () {
	if (this.defaultUrl) {
		this._loadingState = 'loaded'
		this._image.src = this._defaultUrl
	} else {
		this._loadingState = 'none'
	}
}

Bitmap.prototype._bindErrorListener = function () {
	if (this._isIgnore) {
		this._errorListener = this._onDefaultError.bind(this)
	} else {
		this._errorListener = this._loader || Bitmap.prototype._onError.bind(this)
	}
}


Bitmap.prototype._requestImage = function (url) {
	if (Bitmap._reuseImages.length !== 0) {
		this._image = Bitmap._reuseImages.pop();
	} else {
		this._image = new Image();
	}

	if (this._decodeAfterRequest && !this._loader) {
		this._loader = ResourceHandler.createLoader(url, this._requestImage.bind(this, url), this._onError.bind(this));
	}

	this._image = new Image();
	this._url = url;
	this._loadingState = 'requesting';

	if (!Decrypter.checkImgIgnore(url) && Decrypter.hasEncryptedImages) {
		this._loadingState = 'decrypting';
		Decrypter.decryptImg(url, this);
	} else {
		this._image.src = url;

		this._bindErrorListener();
		this._image.addEventListener('load', this._loadListener = Bitmap.prototype._onLoad.bind(this));
		this._image.addEventListener('error', this._errorListener);
	}
}

// 调整bitmap矩形区域内的色调
Bitmap.prototype.adjustRectTone = function(r, g, b, rect) {
    if ((r || g || b) && this.width > 0 && this.height > 0) {
        var context = this._context;
        var imageData = context.getImageData(rect.x, rect.y, rect.width, rect.height);
        var pixels = imageData.data;
        for (var i = 0; i < pixels.length; i += 4) {
            pixels[i + 0] += r;
            pixels[i + 1] += g;
            pixels[i + 2] += b;
        }
        context.putImageData(imageData, rect.x, rect.y);
        this._setDirty();
    }
};